package com.gitee.wsl.collections.map

import com.gitee.wsl.data.store.StateSavedVar
import com.gitee.wsl.data.store.StoreServer

abstract class MapListNode<T : Any>(
    val saveStore: StoreServer,
    val name: String,
    val autoFlush:Boolean=true
) {

    val saveMap = mutableMapOf<String,T>()
    var keySaveList by StateSavedVar(saveStore,name, mutableListOf<String>())

    var flushed=false

    init {
        if(autoFlush)
            flush()
    }

    fun clear(){
        removeAll()
    }

    fun flush(){
        if(flushed) return
        keySaveList.forEach {
            load(it)
        }
        flushed=true
    }

    private fun load(treeId: String){
        saveMap[treeId] = saveStore.getPreferenceOrDefault(treeId,getSampleValue())
    }

    fun saveTree(treeId: String){
        saveStore.putPreference(treeId,saveMap[treeId]!!)
    }

    fun put(treeId: String, value:T){
        saveMap[treeId]=value
        saveStore.putPreference(treeId,value)
        keySaveList.add(treeId)
        flushKeyList()
    }

    fun get(treeId: String):T?{
        if(!keySaveList.contains(treeId))
            return null
        if(saveMap[treeId]==null)
            saveMap[treeId]=saveStore.getPreferenceOrDefault(treeId,getSampleValue())
        return saveMap[treeId]?:getSampleValue()
    }

    fun delete(treeId: String){
        saveMap.remove(treeId)
        saveStore.remove(treeId)
        keySaveList.remove(treeId)
        flushKeyList()
    }

    private fun flushKeyList(){
        this.keySaveList=keySaveList
    }

    fun removeAll(){
        keySaveList.forEach {
            delete(it)
        }
        keySaveList.clear()
        flushKeyList()
    }

    fun containsKey(key:String):Boolean{
        return keySaveList.contains(key)
    }

    fun getValueList(): MutableCollection<T> {
        flush()
        return saveMap.values
    }

    abstract fun getSampleValue():T

}
